import { UaCard, CardCategoryList, TriggerTypeList, CardCategory, TriggerType } from "../../../models/ua-card.model";
import { UaIpEntity } from "../../../models/ua-ip.model";
import { UaUserDeckDto } from "../../../models/ua-user-deck.model";
import { GlobalService } from "../../../services/global.service";
import { LocalStorage } from "../../../services/local-storage.service";
import { UaIpService } from "../../../services/ua-ip.service";
import { UserDeckService } from "../../../services/ua-user-deck.service";
import { formatDate } from "../../../utils/util";

// pages/share/deck-img-share/deck-img-share.page.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    CDN_HOST: GlobalService.FILE_HOST,
    FILE_HOST: GlobalService.STATIC_ASSETS_HOST,
    STATIC_FILE_HOST: GlobalService.STATIC_FILE_HOST,
    qrcode: '',
    idCountMap: {} as { [key: number]: number },
    characterList: [] as UaCard[],
    eventList: [] as UaCard[],
    fieldList: [] as UaCard[],
    showWarnConfirm: false,
    deckName: "",
    logo: "",
    userNickName: "",
    energyCountMap: {} as { [key: string]: number },
    energyTypeKeys: [] as string[],
    categoryCountMap: {} as { [key: string]: number },
    categoryTypeKeys: [] as string[],
    triggerCountMap: {} as { [key: string]: number },
    triggerTypeKeys: [] as string[],
    total: 0,
    totalTrigger: 0,
    myDeck: false,
    r0: '',
    r1: '',
    cr0: '',
    cr1: '',
    ranked: false,
    description: '',
    detailVisible: false,
    detailCard: {} as UaCard,
    max: 0,
    coverCardList: [] as string[],
    deckCardImgList: [] as string[]
  },

  customData: {
    ipId: undefined as number | undefined,
    deckId: undefined as number | undefined,
    authorId: undefined as number | undefined,
    idCountMap: {} as { [key: number]: number },
    cardDeckNoCountMap: {} as { [key: string]: number },
    energyCountOrderMap: {} as { [key: string]: number },
    cardList: [] as UaCard[],
    colorCount: 0,
    finalCount: 0,
    specialCount: 0,
    c0: 0,
    c1: 0,
    fromPrint: false,
    needEffect: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    this.customData.ipId = options.ipId;
    this.customData.deckId = options.deckId;

    wx.setNavigationBarTitle({
      title: '卡组分享'
    });

    UaIpService.fetchUaIp(options.ipId).then((response: UaIpEntity) => {
      if (response) {
        this.setData({
          logo: response.ipTitleLogo
        });
      }
    })
    const categoryCountMap: { [key: string]: number } = {};
    const categoryTypeKeys: string[] = [];
    for (const item of CardCategoryList) {
      categoryTypeKeys.push(item.value.toString().toLowerCase());
      categoryCountMap[item.value.toString().toLowerCase()] = 0;
    }
    const triggerCountMap: { [key: string]: number } = {};
    const triggerTypeKeys: string[] = [];
    for (const item of TriggerTypeList) {
      triggerTypeKeys.push(item.value.toString().toLowerCase());
      triggerCountMap[item.value.toString().toLowerCase()] = 0;
    }

    this.setData({
      categoryTypeKeys,
      categoryCountMap,
      triggerTypeKeys,
      triggerCountMap
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.initDeck();
  },

  initDeck() {
    UserDeckService.findById(this.customData.deckId!).then((response: UaUserDeckDto) => {
      if (response) {
        UserDeckService.getQrCode(response.sn!).then((qrcode: string) => {
          this.setData({
            qrcode: qrcode ?? ''
          })
        });
        this.customData.cardList = response.cardDtoList ?? [];
        const cardMap: { [key: number]: UaCard } = {}
        this.customData.cardList.map((card: UaCard) => {
          cardMap[card.id!] = card;
        })
        const idCountMap: { [key: number]: number } = {};
        const cardDeckNoCountMap: { [key: string]: number } = {};
        for (const item of response.cardList ?? []) {
          idCountMap[item.id!] = item.count!;
          const card = cardMap[item.id!];
          if (card) {
            if (!cardDeckNoCountMap[card.cardDeckNo!]) {
              cardDeckNoCountMap[card.cardDeckNo!] = 0;
            }
            cardDeckNoCountMap[card.cardDeckNo!] += item.count!;
          }
        }
        this.customData.idCountMap = idCountMap;
        this.customData.cardDeckNoCountMap = cardDeckNoCountMap;
        this.customData.authorId = response.userId;
        let coverCardList: string[] = []
        if (!!response.cover) {
          coverCardList = response.cover.split(';');
        }
        this.setData({
          deckName: response.name,
          userNickName: response.userNickName + ' ' + formatDate(new Date(response.updateDate ?? Date.now())),
          myDeck: LocalStorage.getUserInfo()?.id === response.userId,
          ranked: response.ranked,
          description: response.description,
          coverCardList
        })
        this.refreshInfo();
      }
    })
  },

  refreshInfo() {
    const deckNos: string[] = [];
    const characterList: UaCard[] = [];
    const eventList: UaCard[] = [];
    const fieldList: UaCard[] = [];
    const triggerCountMap: { [key: string]: number } = {};
    const categoryCountMap: { [key: string]: number } = {};
    const energyCountMap: { [key: string]: number } = {};
    const energyTypeCountMap: { [key: string]: number } = {};
    const energyTypeKeys: string[] = [];
    const energeColorMap: { [key: string]: string } = {};
    let total = 0;
    let totalTrigger = 0;
    let c0 = 0;
    let c1 = 0;
    const deckCardImgList: string[] = [];
    for (const card of this.customData.cardList) {
      if (!!this.customData.cardDeckNoCountMap[card.cardDeckNo!] && !deckNos.includes(card.cardDeckNo!)) {
        deckNos.push(card.cardDeckNo!);
        const c = this.customData.cardDeckNoCountMap[card.cardDeckNo!];
        if (card.triggerType) {
          if (!triggerCountMap[card.triggerType.toString().toLowerCase()]) {
            triggerCountMap[card.triggerType.toString().toLowerCase()] = 0;
          }
          triggerCountMap[card.triggerType.toString().toLowerCase()] += c;
          totalTrigger += c;
        }
      }
      if (!!this.customData.idCountMap[card.id!]) {
        deckCardImgList.push(card.cardImg!.replace('.png', '.jpg'));
        switch (card.cardCategory) {
          case CardCategory.Character:
            characterList.push(card);
            break;
          case CardCategory.Event:
            eventList.push(card);
            break;
          case CardCategory.Field:
            fieldList.push(card);
            break;
        }
        if (card.cardCategory) {
          if (!categoryCountMap[card.cardCategory.toString().toLowerCase()]) {
            categoryCountMap[card.cardCategory.toString().toLowerCase()] = 0;
          }
          categoryCountMap[card.cardCategory.toString().toLowerCase()] += this.customData.idCountMap[card.id!];
          total += this.customData.idCountMap[card.id!];
        }
        const ek = `${card.needEnergyType!.toLowerCase() + card.needEnergyCount!}`;
        energeColorMap[ek] = card.needEnergyType!.toString();
        if (!energyCountMap[ek]) {
          energyCountMap[ek] = 0;
        }
        if (!energyTypeKeys.includes(ek)) {
          energyTypeKeys.push(ek)
          this.customData.energyCountOrderMap[ek] = card.needEnergyCount!;
        }
        energyCountMap[ek] += this.customData.idCountMap[card.id!];
        if (!energyTypeCountMap[card.needEnergyType!]) {
          energyTypeCountMap[card.needEnergyType!] = 0;
        }
        energyTypeCountMap[card.needEnergyType!] += this.customData.idCountMap[card.id!];
        if (card.needEnergyCount === 0) {
          c0 += this.customData.idCountMap[card.id!];
        }
        if (card.needEnergyCount === 1) {
          c1 += this.customData.idCountMap[card.id!];
        }
        this.customData.c0 = c0;
        this.customData.c1 = c1;
      }
    }
    energyTypeKeys.sort((a, b) => this.customData.energyCountOrderMap[a] - this.customData.energyCountOrderMap[b]);
    let max = 0;
    for (const k of energyTypeKeys) {
      max = Math.max(+energyCountMap[k], max);
    }
    this.customData.finalCount = !!triggerCountMap[TriggerType.Final.toLowerCase()] ? triggerCountMap[TriggerType.Final.toLowerCase()] : 0;
    this.customData.colorCount = !!triggerCountMap[TriggerType.Color.toLowerCase()] ? triggerCountMap[TriggerType.Color.toLowerCase()] : 0;
    this.customData.specialCount = !!triggerCountMap[TriggerType.Special.toLowerCase()] ? triggerCountMap[TriggerType.Special.toLowerCase()] : 0;
    const coverCardList = this.data.coverCardList.filter((item) => deckCardImgList.includes(item));
    this.setData({
      characterList,
      eventList,
      fieldList,
      idCountMap: this.customData.idCountMap,
      categoryCountMap,
      triggerCountMap,
      total,
      totalTrigger,
      energyCountMap,
      energyTypeKeys,
      energeColorMap,
      max,
      coverCardList,
      deckCardImgList
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

})